@echo off
chcp 65001 >nul
title XinSelectCar Development Environment

echo ================================
echo XinSelectCar Development Environment
echo ================================

echo.
echo Checking and terminating processes on ports 3002 and 8080...

REM Check and terminate processes on port 3002 (backend service port)
for /f "tokens=5" %%a in ('netstat -aon ^| findstr :3002') do (
    echo Terminating process on port 3002 with PID: %%a
    taskkill /f /pid %%a 2>nul
)

REM Check and terminate processes on port 8080 (frontend development server port)
for /f "tokens=5" %%a in ('netstat -aon ^| findstr :8080') do (
    echo Terminating process on port 8080 with PID: %%a
    taskkill /f /pid %%a 2>nul
)

echo.
echo Port cleanup completed. Starting backend service and frontend development server...

REM Start backend service in background (hidden window)
cd /d "%~dp0"
echo Starting backend service...
cd backend
start "Backend Service" /b cmd /c "set NODE_ENV=development && node server.js > backend.log 2>&1"
cd ..

REM Wait for backend service to start
timeout /t 3 /nobreak >nul

REM Start frontend development server in background (hidden window)
echo Starting frontend development server...
cd frontend
start "Frontend Development Server" /b cmd /c "npm run serve > frontend.log 2>&1"
cd ..

echo.
echo Starting desktop application...

REM Wait for services to start before launching desktop app
timeout /t 8 /nobreak >nul

REM Start Electron app in foreground (this is the main window users will see)
echo Starting desktop application...
npm start

echo.
echo All services started
echo Backend API service address: http://localhost:3002
echo Frontend development server address: http://localhost:8080
echo.
echo Press any key to close this window...
pause >nul